package com.common.auth.manager;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.api.enums.EnableStateEnum;
import com.common.auth.api.dto.ResourceDto;
import com.common.auth.api.service.ResourceService;
import com.common.auth.api.service.RoleService;
import com.common.auth.api.service.UserRoleRelationService;
import com.common.auth.api.service.UserService;
import com.common.auth.po.RolePo;
import com.common.auth.po.UserPo;
import com.common.auth.po.UserRolePo;
import com.common.auth.util.AuthConstant;
import com.common.template.AbstractModuleInit;
import com.common.util.GenerateSequenceUtil;

import cn.hutool.core.net.URLDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ficus
 * 权限初始化	
 */
@Component
@Slf4j
public class AuthInitManager extends AbstractModuleInit{

	private static String initResource="META-INF/resource.init";
	
	protected String systemId="system";
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private UserRoleRelationService userRoleRelationService;
	
	@Autowired
	private PasswordManager passwordManager;
	
	@Autowired
	private ResourceService menuService;
	
    /**
	 * 初始化用户数据
	 */
	public void init() {
		log.info("AuthInitManager init .....");
		// 初始化系统内所有资源
		initResource();
		// 初始化用户
		initUser();
	}
	
	private void initUser() {
		String roleCode=AuthConstant.ADMIN_ROLE;
		RolePo rolePo=roleService.getById(roleCode);
		if(rolePo==null) {
			rolePo=new RolePo();
			rolePo.setId(roleCode);
			rolePo.setRoleCode(roleCode);
			rolePo.setRoleName("系统管理员");
			rolePo.setRoleDesc("系统管理员");
			rolePo.setCreateTime(new Date());
			rolePo.setUpdateTime(new Date());
			rolePo.setEnableStateEnum(EnableStateEnum.enable.getEunmCode());
			roleService.getBaseMapper().insert(rolePo);
			log.info("init admin role success.");
		}
		
		String userCode=AuthConstant.ADMIN_USER;
		UserPo userPo=userService.getById(userCode);
		if(userPo==null) {
			userPo=new UserPo();
			userPo.setId(userCode);
			userPo.setOrganizationCode(null);
			userPo.setUserCode(userCode);
			userPo.setUserName("超级管理员");
			userPo.setPassword(passwordManager.buildCryPassword(null, userCode));
			userPo.setEmail(null);
			userPo.setCreateTime(new Date());
			userPo.setUpdateTime(new Date());
			userPo.setEnableStateEnum(EnableStateEnum.enable.getEunmCode());
			userService.save(userPo);
			log.info("init admin user success.");
		}
		// 用户和角色关联
		UserRolePo userRolePo = new UserRolePo();
		userRolePo.setRoleCode(roleCode);
		userRolePo.setUserCode(userCode);
		long count=userRoleRelationService.count(Wrappers.query(userRolePo));
		if(count<1) {
			userRoleRelationService.save(userRolePo);
			log.info("init user_role info success.");
		}
	}
	
	private void initResource() {
		log.info("AuthInitManager initResource .....");
		List<ResourceDto> resourceList=new ArrayList<>();
		Enumeration<URL> urls=null;
		try {
			urls = getClass().getClassLoader().getResources(initResource);
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}	
		if(urls!=null) {
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				String urlText = URLDecoder.decode(url.toString(), StandardCharsets.UTF_8);
				try {
					log.info("读取资源信息:"+urlText);
					String resourceInfo=IOUtils.toString(url,StandardCharsets.UTF_8);
					if(StringUtils.isEmpty(resourceInfo)) {
						continue;
					}
					List<ResourceDto> list=JSON.parseArray(resourceInfo, ResourceDto.class);
//					log.info("加载资源信息:"+resourceInfo);
					resourceList.addAll(list);
				} catch (Exception e) {
					e.printStackTrace();
					log.error("读取资源信息异常:"+url+e.getMessage());
				}
			}
		}
		// 新增资源信息
		addResource(resourceList);
	}
	
	private void addResource(List<ResourceDto> resourceList) {
		if(CollectionUtils.isEmpty(resourceList)) {
			return ;
		}
		for (ResourceDto resourceDto : resourceList) {
			ResourceDto record=new ResourceDto(); 
			record.setResourceCode(resourceDto.getResourceCode());
			long count=menuService.count(Wrappers.query(record));
			if(count<1) {
				resourceDto.setId(GenerateSequenceUtil.generateSequenceNo());
				resourceDto.setCreateTime(new Date());
				resourceDto.setUpdateTime(new Date());
				menuService.add(resourceDto);	
			}
			List<ResourceDto> children = resourceDto.getChildren();
			addResource(children);
		}
	}
}
